<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Map结构</title>
</head>
<body>
    <h1>Map结构</h1>

    <script>
        // 使用Map替代对象
        // bad
        const items = {};
        items[getKey('foo')] = 'foo';

        // good
        const items = new Map();
        items.set(getKey('foo'), 'foo');

        // Map的键可以是任意类型
        const map = new Map();
        const user = { id: 1 };
        map.set(user, 'userInfo');

        // Map的遍历
        for (const [key, value] of map) {
            console.log(key, value);
        }

        // 实际应用示例
        // 缓存系统
        class Cache {
            constructor() {
                this.cache = new Map();
            }

            set(key, value, ttl = 60000) {
                const expires = Date.now() + ttl;
                this.cache.set(key, { value, expires });
                return this;
            }

            get(key) {
                const data = this.cache.get(key);
                if (!data) return null;
                if (Date.now() > data.expires) {
                    this.cache.delete(key);
                    return null;
                }
                return data.value;
            }

            delete(key) {
                return this.cache.delete(key);
            }

            clear() {
                this.cache.clear();
            }
        }

        // 状态管理
        class StateManager {
            constructor() {
                this.states = new Map();
                this.listeners = new Map();
            }

            setState(key, value) {
                this.states.set(key, value);
                if (this.listeners.has(key)) {
                    this.listeners.get(key).forEach(listener => 
                        listener(value)
                    );
                }
            }

            getState(key) {
                return this.states.get(key);
            }

            subscribe(key, listener) {
                if (!this.listeners.has(key)) {
                    this.listeners.set(key, new Set());
                }
                this.listeners.get(key).add(listener);
            }
        }
    </script>
</body>
</html> 